<template>
  <xn-dialog
    custom-class="user-reset-phone-dialog"
    title="更换手机号"
    :visible.sync="selfVisible"
    @close="onDialogHide">
    <div class="content">
      <div class="step-navs">
        <step-nav :arrived-idx="arrivedStepIdx" v-model="activedStepIdx">
          <step-item v-for="(item, idx) in navData" :idx="idx" :key="item.num">
            <step-item-svg
              :option="item"
              :actived="activedStepIdx === idx"
              :passed="arrivedStepIdx > idx"
              :is-end="idx === navData.length - 1" />
          </step-item>
        </step-nav>
      </div>
      <div class="step-init" v-if="activedStepIdx === 0">
        <el-form ref="checkFrom" :model="form" label-width="100px" label-suffix="：" :rules="rules">
          <div class="binded-phone">已绑定的手机：{{ userInfo.telephone }}</div>
          <el-form-item label="验证码" prop="checkSmsCode">
            <el-input v-model="form.checkSmsCode" placeholder="请输入验证码" :maxlength="6" clearable>
              <el-button
                slot="append"
                class="send-btn"
                :class="{ disabled: sendCodeStatus === 'send' }"
                @click="sendCode(1)">
                {{ codeBtnDisplay }}
              </el-button>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="btn-view">
          <el-button type="primary" @click="checkOriPhone">下一步</el-button>
        </div>
      </div>
      <div class="step-change" v-if="activedStepIdx === 1">
        <el-form ref="changeForm" :model="form" label-width="100px" label-suffix="：" :rules="rules">
          <el-form-item label="手机号" prop="telephone">
            <el-input v-model="form.telephone" placeholder="请输入手机号" :maxlength="11" clearable></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="smsCode">
            <el-input v-model="form.smsCode" placeholder="请输入验证码" :maxlength="6" clearable>
              <el-button
                slot="append"
                class="send-btn"
                :class="{ disabled: sendCodeStatus === 'send' }"
                @click="sendCode(2)">
                {{ codeBtnDisplay }}
              </el-button>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="btn-view">
          <el-button type="primary" @click="goNextStep">下一步</el-button>
        </div>
      </div>
      <div class="step-finshed" v-if="activedStepIdx === 2">
        <div class="success-icon"><i class="el-icon-circle-check"></i></div>
        <p>手机号变更成功！</p>
        <p class="sub">绩效办重要工作通知将通过该手机号通知到您！</p>
        <div class="btn-view">
          <el-button type="primary" @click="onDialogHide">完成</el-button>
        </div>
      </div>
    </div>
  </xn-dialog>
</template>
<script>
import { getBingPhoneCode, modifyTelephone, checkSmsCode } from '@api/modules/user.js'
import XnDialog from '@com/xnDialog.vue'
import { phoneReg, checkCodeReg } from '@utility/regExps.js'
import StepNav from '@com/StepNav/index.vue'
import StepItem from '@com/StepNav/StepItem.vue'
import StepItemSvg from '@com/StepNav/StepItemSvg.vue'
import { USER_PHONE_EDIT_TYPE } from '@utility/dict'

export default {
  name: 'UserResetPhoneDialog',
  components: {
    XnDialog,
    StepNav,
    StepItem,
    StepItemSvg,
  },
  props: {
    visible: {
      type: Boolean,
    },
  },
  data() {
    return {
      selfVisible: false,
      isForceEdit: false,
      navData: [
        { num: 1, title: '验证身份' },
        { num: 2, title: '修改手机号码' },
        { num: 3, title: '完成更换' },
      ],
      arrivedStepIdx: 0,
      activedStepIdx: 0,
      form: {
        telephone: '',
        smsCode: '',
        checkSmsCode: '',
      },
      rules: {
        checkSmsCode: [
          {
            required: true,
            message: '请输入有效的验证码',
            trigger: 'blur',
            pattern: checkCodeReg,
          },
        ],
        telephone: [
          {
            required: true,
            message: '请输入有效的手机号',
            trigger: 'blur',
            pattern: phoneReg,
          },
        ],
        smsCode: [
          {
            required: true,
            message: '请输入有效的验证码',
            trigger: 'blur',
            pattern: checkCodeReg,
          },
        ],
      },
      cutdownSec: 0,
      sendCodeStatus: 'init', // init, send, retry
      cutdownTimer: null,
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters['role/userInfo']
    },
    codeBtnDisplay() {
      if (this.sendCodeStatus === 'init') {
        return '发送验证码'
      } else if (this.sendCodeStatus === 'send') {
        return this.cutdownSec + ' 秒'
      }
      return '重新发送'
    },
  },
  watch: {
    visible(visible) {
      this.selfVisible = visible
      if (!visible) {
        this.form.telephone = ''
        this.form.smsCode = ''
        this.form.checkSmsCode = ''
        this.clearCutdownTimer()
        this.sendCodeStatus = 'init'
        this.arrivedStepIdx = 0
        this.activedStepIdx = 0
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    onDialogHide() {
      this.$emit('update:visible', false)
      this.$emit('closed')
    },

    sendCode(step = 1) {
      if (this.sendCodeStatus === 'send') {
        return
      }
      if (step === 1) {
        getBingPhoneCode(USER_PHONE_EDIT_TYPE.change, '', { step: step }).then(res => {
          if (res.code === 0) {
            this.startCutdown()
          }
        })
      } else {
        if (this.form.telephone === this.userInfo.telephone) {
          this.$message.error('新手机号与原手机号相同！')
          return
        }
        this.$refs.changeForm.validateField('telephone', invalid => {
          if (!invalid) {
            getBingPhoneCode(USER_PHONE_EDIT_TYPE.change, this.form.telephone, {
              step: step,
              smsCode: this.form.checkSmsCode,
            }).then(res => {
              if (res.code === 0) {
                this.startCutdown()
              } else if (res.msg === '第一步校验失败') {
                this.arrivedStepIdx = 0
                this.activedStepIdx = 0
                this.sendCodeStatus = 'retry'
              }
            })
          }
        })
      }
    },
    startCutdown() {
      this.clearCutdownTimer()
      this.sendCodeStatus = 'send'
      this.cutdownSec = 60
      this.cutdownTimer = setInterval(() => {
        this.cutdownSec--
        if (this.cutdownSec <= 0) {
          this.clearCutdownTimer()
          this.sendCodeStatus = 'retry'
        }
      }, 1000)
    },
    clearCutdownTimer() {
      if (this.cutdownTimer) {
        clearInterval(this.cutdownTimer)
        this.cutdownSec = 0
      }
    },
    checkOriPhone() {
      if (this.sendCodeStatus !== 'init') {
        this.$refs.checkFrom.validate(valid => {
          if (valid) {
            checkSmsCode(this.userInfo.telephone, this.form.checkSmsCode).then(res => {
              if (res.code === 0) {
                this.arrivedStepIdx = 1
                this.activedStepIdx = 1
                this.sendCodeStatus = 'init'
                this.clearCutdownTimer()
              }
            })
          }
        })
      } else {
        this.$message.warning('请先获取验证码！')
      }
    },
    goNextStep() {
      // if (this.arrivedStepIdx === 0) {
      //   if (this.sendCodeStatus !== 'init') {
      //     this.$refs.checkFrom.validate(valid => {
      //       if (valid) {
      //         this.arrivedStepIdx = 1
      //         this.activedStepIdx = 1
      //         this.sendCodeStatus = 'init'
      //         this.clearCutdownTimer()
      //       }
      //     })
      //   } else {
      //     this.$message.warning('请先获取验证码！')
      //   }
      // } else if (this.arrivedStepIdx === 1) {
      if (this.sendCodeStatus !== 'init') {
        this.$refs.changeForm.validate(valid => {
          if (valid) {
            modifyTelephone(
              this.form.telephone,
              this.form.smsCode,
              USER_PHONE_EDIT_TYPE.change,
              this.form.checkSmsCode
            ).then(res => {
              if (res.code === 0) {
                this.$message.success('手机号修改成功！')
                this.userInfo.telephone = this.form.telephone
                this.$store.commit('role/setUserInfo', this.userInfo)
                this.arrivedStepIdx++
                this.activedStepIdx++
              }
            })
          }
        })
      } else {
        this.$message.warning('请先获取验证码！')
      }
      // }
    },
  },
}
</script>
<style lang="scss" scoped>
.user-reset-phone-dialog {
  ::v-deep &.el-dialog {
    width: 550px !important;
    height: 350px;
  }
  .content {
    height: 100%;
    padding-top: 20px;
    .step-navs {
      margin-bottom: 30px;
    }
    .send-btn {
      width: 120px;
      &.disabled {
        cursor: not-allowed;
      }
    }
    .btn-view {
      text-align: center;
      margin-top: 20px;
      .el-button {
        width: 160px;
      }
    }
    .binded-phone {
      text-align: center;
      font-size: 16px;
      margin-bottom: 30px;
    }
    .step-finshed {
      text-align: center;
      .success-icon {
        font-size: 46px;
        color: #67c23a;
      }
      p {
        margin: 10px;
        font-size: 16px;
        color: #333;
      }
      .sub {
        font-size: 14px;
        color: #666;
      }
    }
    .footer {
      text-align: center;
      .btn-sure {
        padding: 10px 50px;
      }
    }
  }
}
</style>
